#include "searchform.h"

#include "searchitem.h"
#include "ui_searchform.h"

#include <Application.h>
#include <QDebug>
#include <QTimer>

SearchForm::SearchForm(QWidget* parent) : QWidget(parent),
                                          ui(new Ui::SearchForm) {
    ui->setupUi(this);
    ui->lineEdit->setClearButtonEnabled(true);
    setAttribute(Qt::WA_DeleteOnClose, true);
    CommonUtils::loadStyleSheet(this, "searchform");
    connect(Application::instance(), &Application::signalSearchAuthor, this, &SearchForm::onSearchAuthor);
    connect(Application::instance(), &Application::signalSearchGroup, this, &SearchForm::onSearchGroup);
}

SearchForm::~SearchForm() {
    delete ui;
}

void SearchForm::showlist() {
}

void SearchForm::addWidget(std::shared_ptr<UserInfo> info) {
    auto item     = new QListWidgetItem(ui->listWidget);
    auto userItem = new SearchItem(ui->listWidget);
    userItem->setInfo(info);

    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, userItem);
    item->setSizeHint(QSize(172, 74));
}

void SearchForm::onSearchAuthor(std::vector<std::shared_ptr<UserInfo>> users) {
    ui->listWidget->clear();
    for (auto&& i : users) {
        if (i->userid() != Application::Myself().userid())
            addWidget(i);
    }
}

void SearchForm::onSearchGroup(std::vector<std::shared_ptr<ChatRoomInfo>> rooms) {
}

void SearchForm::on_lineEdit_textChanged(const QString& arg1) {
    if (!timer) {
        timer = new QTimer(this);
        timer->setSingleShot(true);
        connect(timer, &QTimer::timeout, [=]() {
            std::string text = ui->lineEdit->text().toStdString();
            if (isSearchAuthor) {
                Application::instance()->SearchAuthor(text);
            }
            else {
                Application::instance()->SearchGroup(text);
            }
        });
    }

    if (arg1 == "") {
        timer->stop();
    }
    else {
        timer->start(500);
    }
}
